// pages/addLease/addLease.js
var util = require('../../utils/util.js')
var common = require('../../utils/common.js');
const app = getApp();
var that = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dateSelectTab: [{
      value: "3个月",
      y: 0,
      m: 3,
      check: false
    }, {
      value: "6个月",
      y: 0,
      m: 6,
      check: false
    }, {
      value: "1年",
      y: 1,
      m: 0,
      check: false
    }, {
      value: "2年",
      y: 2,
      m: 0,
      check: false
    }, {
      value: "3年",
      y: 3,
      m: 0,
      check: false
    }], //时间
    // feeList: [{ id: '', pid: 1, sequence: 12, itemKey: "12", itemName: "水费", chargeType: 0, nowNum: 0, unitCost: 0 }, { id: '', pid: 1, sequence: 6, itemKey: "6", itemName: "电费", chargeType: 0, nowNum: 0, unitCost: 0 }],//费用项目列表
    feeList: [], //费用列表
    foregiftList: [], //押金列表
    rentalDeposit: {
      chargeType: 1,
      checked: true,
      id: "",
      itemKey: "1",
      itemName: "房屋押金",
      pid: 33,
      sequence: 1,
      unitCost: "",
    }, //押金费用
    roomsId: '', //房间ID
    tenantData: {}, //租户信息
    roomsInfo: '', //房间信息
    thatTime: "", //当前日期用于时间选择
    startTime: "", //合同开始时间
    endTime: "", //合同结束时间
    payTypeList: [], //付款方式列表
    paytypeindex: 0, //付款方式下标
    monthlyfee: '', //每月租金
    billEndTime: '', //首期账单结束时间
    remark: '', //备注
    total: 0, //总计

    WEmodal: true, //水电输入弹窗
    WEItem: {}, //弹窗数据对象
    WEItemIndex: 0, //水电点击下标

    feeListmodal: true, //收费项选择弹窗
    modalFeeList: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
    modalType: 0, //0表示modal为费用添加 1 押金添加
  },

  selectRooms: function() {
    wx.navigateTo({
      url: '../selectRooms/selectRooms',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    this.initData(); //
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var tenantData = wx.getStorageSync("tenant");
    wx.removeStorageSync("tenant");
    if (tenantData) {
      this.setData({
        tenantData: tenantData
      })

    }

    var selectRoomsId = wx.getStorageSync("selectRoomsId");
    wx.removeStorageSync("selectRoomsId");
    if (selectRoomsId) {
      this.setData({
        roomsId: selectRoomsId
      })
      that.getRoomsInfo();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  //初始化
  initData: function() {
    //付款方式
    common._get('/wx/dict/list', {
        key: 'CHARGEMODE'
      },
      //成功
      function(res) {
        if (res.data.success) {
          that.setData({
            payTypeList: res.data.data,
          })
        }
        that.totalFun();
      });

    //时间初始化
    that.setData({
      thatTime: util.formatTimeYear(new Date, 0, 0),
      startTime: util.formatTimeYear(new Date, 0, 0),
      endTime: util.formatTimeYear(new Date(), 1, 0, 1),
    })
    //获取首期账单结束时间
    that.countFirstBillTime();
    //获取费用列表
    that.getFeeData('CHARGEITEM');
    //获取押金列表
    that.getFeeData('FOREGIFT');
  },

  //获取房间信息
  getRoomsInfo: function() {
    console.log("获取房间信息：" + that.data.roomsId);
    var pos = 0; //收费方式下标
    common._get('/wx/room/getroominfo', {
        roomId: that.data.roomsId,
      },
      //成功
      function(res) {
        for (var i in that.data.payTypeList) {
          if (that.data.payTypeList[i].key == res.data.data.chargemode) {
            pos = i;
            break;
          }
        }
        if (res.data.success) {
          that.setData({
            roomsInfo: res.data.data.houseName + "-" + res.data.data.roomcode,
            monthlyfee: res.data.data.price,
            paytypeindex: pos
          })
          //要判断是否获取到费用
          that.getFeeModal();
          that.countFirstBillTime();
          that.countYj();
          that.totalFun();
        }

      });
  },
  getFeeModal: function() {
    //每月固定生成费用
    var fees = wx.getStorageSync("feeList");
    if (fees) {
      that.setData({
        feeList: fees
      })
    }
    console.log(that.data.feeList)
    // 押金费用
    var feey = wx.getStorageSync("foregiftList")
    if (feey) {
      that.setData({
        foregiftList: feey
      })
    }
    that.totalFun();
  },

  //开始时间选择
  startTimeChange: function(e) {
    this.setData({
      startTime: e.detail.value
    })
    that.countFirstBillTime();
  },
  //结束时间选择
  endTimeChange: function(e) {
    this.setData({
      endTime: e.detail.value
    })
  },
  //时间项选择
  timeItemClick: function(e) {
    var index = e.currentTarget.dataset.index;
    var obj = this.data.dateSelectTab[index];
    var date1 = this.data.startTime.split("-");
    this.setData({
      endTime: util.formatTimeYear(new Date(date1[0], date1[1] - 1, date1[2]), obj.y, obj.m, 1),
    })
  },
  //付款方式选择
  payTypeChabge: function(e) {
    this.setData({
      paytypeindex: e.detail.value,
    })
    this.countYj();
    that.countFirstBillTime();
    that.totalFun();
  },
  //每月租金输入
  monthlyfeeInput: function(e) {
    this.setData({
      monthlyfee: e.detail.value,
    })
    this.countYj();
    that.totalFun();
  },
  //房屋押金输入
  rentalDepositInput: function(e) {
    that.data.rentalDeposit.unitCost = e.detail.value
    this.setData({
      rentalDeposit: that.data.rentalDeposit,
    })
    that.totalFun();
  },

  //计算押金
  countYj: function() {
    var n = Number(this.data.payTypeList[this.data.paytypeindex] ? this.data.payTypeList[this.data.paytypeindex].key : 1)
    var sum = ''
    switch (n) {
      case 1:
        that.data.rentalDeposit.unitCost = Number(this.data.monthlyfee) * 1
        break;
      case 2:
        that.data.rentalDeposit.unitCost = Number(this.data.monthlyfee) * 1
        break;
      case 3:
        that.data.rentalDeposit.unitCost = Number(this.data.monthlyfee) * 1
        break;
      case 4:
        that.data.rentalDeposit.unitCost = Number(this.data.monthlyfee) * 2
        break;
      case 5:
        that.data.rentalDeposit.unitCost = Number(this.data.monthlyfee) * 2
        break;
    }
    this.setData({
      rentalDeposit: that.data.rentalDeposit,
    })
  },
  //根据key获取账单的周期
  cuntPayType: function(key) {
    key = parseInt(key)
    var pay = 1;
    switch (key) {
      case 1:
        pay = 1
        break;
      case 2:
        pay = 2
        break;
      case 3:
        pay = 3
        break;
      case 4:
        pay = 2
        break;
      case 5:
        pay = 3
        break;
    }
    return pay;
  },

  //计算首期账单时间
  countFirstBillTime: function() {
    var key = 1;
    if (this.data.payTypeList[this.data.paytypeindex]) {
      key = this.data.payTypeList[this.data.paytypeindex].key;
    }
    var payType = this.cuntPayType(key);
    var date1 = this.data.startTime.split("-");
    this.setData({
      billEndTime: util.formatTimeYear(new Date(date1[0], date1[1] - 1, date1[2]), 0, payType, 1),
    })
  },
  //费用项输入
  feeInput: function(e) {
    var value = e.detail.value;
    var indx = e.currentTarget.dataset.index;
    this.data.feeList[indx].unitCost = value;
    that.totalFun();
  },
  //押金输入
  feeyInput: function(e) {
    var value = e.detail.value;
    var indx = e.currentTarget.dataset.index;
    this.data.foregiftList[indx].unitCost = value;
    that.totalFun();
  },

  //删除费用项
  deleteFeeItem: function(e) {
    var indx = e.target.dataset.index;
    that.data.feeList[indx].check = false;
    that.data.feeList[indx].checkM = false;
    var fee = that.data.feeList;
    that.setData({
      feeList: fee
    })
    that.totalFun();
  },
  //删除押金项
  deleteYjItem: function(e) {
    var indx = e.target.dataset.index;
    that.data.foregiftList[indx].check = false;
    that.data.foregiftList[indx].checkM = false;
    var fee = that.data.foregiftList;
    that.setData({
      foregiftList: fee
    })
    that.totalFun();
  },

  //点击水电项
  WEFeeItemClick: function(e) {
    var indx = e.currentTarget.dataset.index;
    this.setData({
      WEItemIndex: indx,
      WEmodal: false,
      WEItem: this.data.feeList[indx]
    })
  },
  //初始读数输入
  nowNumInput: function(e) {
    var value = e.detail.value;
    // var indx = e.currentTarget.dataset.index;
    this.data.WEItem.nowNum = value == '' ? 0 : value;
  },
  //水电单价输入
  WEItemChange: function(e) {
    var value = e.detail.value;
    // var indx = e.currentTarget.dataset.index;
    this.data.WEItem.unitCost = value == '' ? 0 : value;
  },
  //确认
  confirm: function() {
    this.data.feeList[this.data.WEItemIndex] = this.data.WEItem;
    this.setData({
      feeList: this.data.feeList,
      WEmodal: true,
    })
    that.totalFun();
  },
  //取消
  cancel: function() {
    this.setData({
      WEmodal: true,
    })
  },

  //点击添加费用
  addFeeItemClick: function(e) {
    var tag = e.currentTarget.dataset.tag;
    var fees = tag == 0 ? that.data.feeList : that.data.foregiftList;
    this.setData({
      feeListmodal: false,
      modalFeeList: fees,
      modalType: tag
    })
  },
  //费用选择弹窗确认
  confirmFee: function() {
    that.data.modalType
    var fees = that.data.modalFeeList;
    for (var i in fees) {
      if (fees[i].checkM) {
        fees[i].check = true;
      }
    }
    if (that.data.modalType == 0) {
      this.setData({
        feeListmodal: true,
        feeList: fees
      })
    } else {
      this.setData({
        feeListmodal: true,
        foregiftList: fees
      })
    }
    that.totalFun();
  },
  //费用选择弹窗取消
  cancelFee: function() {
    this.setData({
      feeListmodal: true,
    })
  },
  //点击选择费用项
  modalItemClick: function(e) {
    var index = e.currentTarget.dataset.index;
    that.data.modalFeeList[index].checkM = !that.data.modalFeeList[index].checkM
    this.setData({
      modalFeeList: that.data.modalFeeList
    })
  },
  //备注输入
  remarkInput: function(e) {
    this.setData({
      remark: e.detail.value,
    })
  },

  //获取费用列表
  getFeeData: function(key) {
    var pos = -1;
    var url = "/wx/dict/list";
    var data = {
      key: key
    };
    var success = function(res) {
      var change = {
        "id": "id",
        "key": "itemKey",
        "value": "itemName",
        "pid": "pid",
        "sequence": "sequence",
        "check": "check",
        "ckeckM": "ckeckM"
      }
      var fydata = res.data.data;
      if (fydata) {
        for (var i = 0; i < fydata.length; i++) {
          fydata[i].id = "";
          fydata[i].check = false;
          fydata[i].ckeckM = false;
          that.replace(fydata[i], change);
          if (fydata[i].itemName == "水费" || fydata[i].itemName == "电费") {
            fydata[i]["chargeType"] = 0;
          } else {
            fydata[i]["chargeType"] = 1;
          }
          //删除房屋押金（因为房屋押金为必须项）
          if (key == 'FOREGIFT' && fydata[i].itemKey == 1) {
            pos = i;

          }
        }
        fydata.splice(pos, 1);
        if (key == 'CHARGEITEM') {
          that.setData({
            feeList: fydata,
          })
        } else {
          that.setData({
            foregiftList: fydata,
          })

        }

      }
    };
    common._get(url, data, success)
  },
  //换key
  replace: function(target, change) {
    for (var key in target) {
      target[change[key]] = target[key];
      if (change[key] != key) {
        delete target[key];
      }
    }
  },

  // 总计
  totalFun: function() {
    var arr = [];
    var arry = [];
    var data = this.data;
    //获取每月固定生成费用
    var fees = [];
    for (var i in data.feeList) {
      if (data.feeList[i].check) {
        var pos = arr.push(data.feeList[i]);
      }
    }
    //获取押金费用
    var feey = [];
    for (var i in data.foregiftList) {
      if (data.foregiftList[i].check) {
        arry.push(data.foregiftList[i]);
      }
    }

    var n = Number(this.data.payTypeList[this.data.paytypeindex] ? this.data.payTypeList[this.data.paytypeindex].key : 1);
    console.log("付款方式下标"+n)
    var sum = 0;
    //费用项
    for (var i in arr) {
      if (arr[i].chargeType == 1) {
        if (arr[i].unitCost && arr[i].unitCost > 0) {
          sum = sum + Number(arr[i].unitCost)
        }
      }
    }
    var fwyj = 0;
    //费用项
    for (var i in arry) {
      if (Number(arry[i].itemKey) == 1) {
        fwyj = Number(arry[i].unitCost);
      } else {
        if (arry[i].unitCost && arry[i].unitCost > 0) {
          sum = sum + Number(arry[i].unitCost)
        }
      }
    }

    switch (n) {
      case 1:
        sum = sum + (Number(this.data.monthlyfee) * 1)
        break;
      case 2:
        sum = sum + (Number(this.data.monthlyfee) * 2)
        break;
      case 3:
        sum = sum + (Number(this.data.monthlyfee) * 3)
        break;
      case 4:
        sum = sum + (Number(this.data.monthlyfee) * 2)
        break;
      case 5:
        sum = sum + (Number(this.data.monthlyfee) * 3)
        break;
      default:
        sum = sum + (Number(this.data.monthlyfee) * 1)
        break;
    }
    //加上押金
    console.log("sum:" + sum + " fwyj:" + fwyj+ " 押金:" + that.data.rentalDeposit.unitCost);
    sum = sum + fwyj + Number(this.data.rentalDeposit.unitCost);
    this.setData({
      total: sum,
    })

  },


  //要提交的数据
  submitData: function() {
    var data = this.data;
    //获取每月固定生成费用
    var fees = [];
    for (var i in data.feeList) {
      if (data.feeList[i].check) {
        var pos = fees.push(data.feeList[i]);
        delete fees[pos - 1].check;
        delete fees[pos - 1].checkM;
      }
    }
    // console.log(JSON.stringify(fees))
    // //获取押金费用
    var feey = [];
    for (var i in data.foregiftList) {
      if (data.foregiftList[i].check) {
        feey.push(data.foregiftList[i]);
      }
    }
    feey.push(data.rentalDeposit);
    var datas = {
      starttime: data.startTime, //合同开始时间
      monthlyfee: data.monthlyfee, //月租金
      chargemode: data.payTypeList[data.paytypeindex].key, //收费方式
      remark: data.remark ? data.remark : '', //备注
      memberId: '', //租户ID
      mobile: data.tenantData.phone, //租户手机号
      username: data.tenantData.userName, //租户姓名
      idNumber: data.tenantData.idCardNumber, //身份证号码
      sex: data.tenantData.sex, //租户性别(0--女 1--男)
      endtime: data.endTime, //合同截止时间
      gifts: feey, //押金列表
      roomId: data.roomsId, //房间ID
      items: fees, //固定费用列表
    }
    return datas;
  },
  submitBnt: function() {
    if (this.data.roomsId == '') {
      wx.showToast({
        title: '请选择入住房间',
        image: '../../image/shibai.png'
      })
      return;
    }
    var data = that.submitData();

    common._get('/wx/contract/save', data,
      //成功
      function(res) {
        console.log(res.data);
        //手机获取信息是否成功
        if (res.data.success) {
          app.setRefresh();
          wx.setStorageSync('modifyRoom', 'modifyRoom');
          //成功添加入住
          wx.setStorageSync('addContract', "addContract")
          wx.showModal({
            title: '提示',
            content: '已经成功保存入住',
            showCancel: false,
            success: function(resm) {
              if (resm.confirm) {
                wx.redirectTo({
                  url: '../receiptDetails/receiptDetails?chargeid=' + res.data.data.chargeId + '&add_contract=yes',
                })
              }
            }
          })
        }
      });

  },

  //长按页面保存费用模板
  logtap: function() {
    wx.showModal({
      title: '提示',
      content: '确定保存当前费用模板吗？',
      success: function(res) {
        if (res.confirm) {
          var data = that.data;
          for (var i in data.feeList) {
            if (parseInt(data.feeList[i].itemKey) == 12 || data.feeList[i].itemKey == 6) {
              data.feeList[i].nowNum = '';
            }
          }
          //每月固定生成费用
          wx.setStorageSync("feeList", data.feeList)
          // 押金费用
          wx.setStorageSync("foregiftList", data.foregiftList)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }

})